package petrochina.company.electric.ui.fragment;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.hjq.widget.layout.SettingBar;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

import petrochina.company.electric.R;
import petrochina.company.electric.aop.SingleClick;
import petrochina.company.electric.app.TitleBarFragment;
import petrochina.company.electric.http.api.LoginApi;
import petrochina.company.electric.http.api.TaskApplyAddApi;
import petrochina.company.electric.http.api.TaskApplyDataApi;
import petrochina.company.electric.http.model.HttpData;
import petrochina.company.electric.model.TaskApplyCircuitData;
import petrochina.company.electric.model.TaskApplyEquipData;
import petrochina.company.electric.model.TaskApplyRegionData;
import petrochina.company.electric.model.TaskApplyResult;
import petrochina.company.electric.other.GridSpacingItemDecoration;
import petrochina.company.electric.ui.activity.HomeActivity;
import petrochina.company.electric.ui.activity.LoginActivity;
import petrochina.company.electric.ui.adapter.ApplyBreakerNumAdapter;
import petrochina.company.electric.ui.dialog.MenuDialog;
import petrochina.company.electric.ui.dialog.MultiMenuDialog;
import petrochina.company.electric.widget.XCollapsingToolbarLayout;

/**
 * desc   : 申请 Fragment
 */
public final class ApplyFragment extends TitleBarFragment<HomeActivity>
        implements
        XCollapsingToolbarLayout.OnScrimsListener {

    private TextView mApplyUserName;
    private AppCompatEditText mEtTaskContent;
    private SettingBar mLineDoubleNameSb;
    private SettingBar mAreaSb;
    private SettingBar mBreakerNum;
    private SettingBar mPowerMultiple;
    private SettingBar mStoredMultiple;

    private RecyclerView mRvPower;
    private RecyclerView mRvStored;

    private ApplyBreakerNumAdapter mPowerAdapter, mStoredAdapter;

    private MMKV mmkv;
    private Gson gson;

    private LoginApi.Bean loginData;
    private TaskApplyDataApi.Bean mData;
    private Integer currentCircuitIndex;
    private Integer currentRegionIndex;
    private Integer currentEquipIndex;
    private List<Integer> selectElectricEquipIndex = new ArrayList<>();
    private List<Integer> selectEnergyEquipIndex = new ArrayList<>();


    public static ApplyFragment newInstance() {
        return new ApplyFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.apply_fragment;
    }

    @Override
    protected void initView() {
        mmkv = MMKV.defaultMMKV();
        gson = new Gson();
        String loginStr = mmkv.getString("loginData", null);
        if (!TextUtils.isEmpty(loginStr)) {
            loginData = gson.fromJson(loginStr, LoginApi.Bean.class);
        }
        if (loginData == null) {
            ToastUtils.show("请登录！");
            LoginActivity.start(requireContext());
            finish();
        }

        mApplyUserName = findViewById(R.id.tv_apply_user_name);
        mEtTaskContent = findViewById(R.id.et_task_content);
        mLineDoubleNameSb = findViewById(R.id.sb_line_double_name);
        mAreaSb = findViewById(R.id.sb_apply_area);
        mBreakerNum = findViewById(R.id.sb_breaker_num);
        mPowerMultiple = findViewById(R.id.sb_power_multiple);
        mStoredMultiple = findViewById(R.id.sb_stored_multiple);
        mRvPower = findViewById(R.id.rv_apply_power);
        mRvStored = findViewById(R.id.rv_apply_stored);

        setOnClickListener(R.id.sb_line_double_name, R.id.sb_apply_area, R.id.sb_breaker_num,
                R.id.sb_power_multiple, R.id.sb_stored_multiple,
                R.id.btn_apply_cancel, R.id.btn_apply_commit);


        mPowerAdapter = new ApplyBreakerNumAdapter(getAttachActivity());
        mStoredAdapter = new ApplyBreakerNumAdapter(getAttachActivity());

        int spacingVertical = getResources().getDimensionPixelSize(R.dimen.dp_10);
        int spacingHorizontal = getResources().getDimensionPixelSize(R.dimen.dp_10);
        int spanCount = 4;

        GridLayoutManager glmPower = new GridLayoutManager(getContext(), spanCount);
        mRvPower.setLayoutManager(glmPower);
        mRvPower.addItemDecoration(new GridSpacingItemDecoration(spacingVertical, spacingHorizontal, spanCount));
        mRvPower.setAdapter(mPowerAdapter);

        GridLayoutManager glmStoredPower = new GridLayoutManager(getContext(), spanCount);
        mRvStored.setLayoutManager(glmStoredPower);
        mRvStored.addItemDecoration(new GridSpacingItemDecoration(spacingVertical, spacingHorizontal, spanCount));
        mRvStored.setAdapter(mStoredAdapter);
    }

    @Override
    protected void initData() {
        mApplyUserName.setText(loginData.getStaffName());
        getPageData();
    }

    private void getPageData() {
        EasyHttp.get(this)
                .api(new TaskApplyDataApi())
                .request(new HttpCallback<HttpData<TaskApplyDataApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<TaskApplyDataApi.Bean> result) {
                        mData = result.getData();
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }

                });
    }

    /**
     * 点击选择
     *
     * @param view
     */
    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sb_line_double_name:
                selectLineDoubleName();
                break;
            case R.id.sb_apply_area:
                selectArea();
                break;
            case R.id.sb_breaker_num:
                selectBreakerNum();
                break;
            case R.id.sb_power_multiple:
                selectPowerList(0);
                break;
            case R.id.sb_stored_multiple:
                selectPowerList(1);
                break;
            case R.id.btn_apply_cancel:
                cleanData();
                break;
            case R.id.btn_apply_commit:
                submit();
                break;
        }
    }

    private void submit() {
        if (mEtTaskContent.getText() == null || TextUtils.isEmpty(mEtTaskContent.getText().toString().trim())) {
            ToastUtils.show("请填写工作任务！");
            return;
        } else if (currentCircuitIndex == null || currentCircuitIndex == -1) {
            ToastUtils.show("请选择线路双名称！");
            return;
        } else if (currentRegionIndex == null || currentRegionIndex == -1) {
            ToastUtils.show("请选择所在地区！");
            return;
        } else if (currentEquipIndex == null || currentEquipIndex == -1) {
            ToastUtils.show("请选择断路器编号！");
            return;
        } else if (selectElectricEquipIndex == null || selectElectricEquipIndex.size() == 0) {
            ToastUtils.show("请选择发电低压断路器编号！");
            return;
        } else if (selectEnergyEquipIndex == null || selectEnergyEquipIndex.size() == 0) {
            ToastUtils.show("请选择储能低压断路器编号！");
            return;
        }
        String taskContent = mEtTaskContent.getText().toString().trim();
        long circuitId = mData.getCircuits().get(currentCircuitIndex).getId();
        long regionId = mData.getRegions().get(currentRegionIndex).getId();
        long equipId = mData.getEquips().get(currentEquipIndex).getId();
        StringBuffer electricEquips = new StringBuffer();
        for (Integer index : selectElectricEquipIndex) {
            if (index != -1) {
                if (electricEquips.length() > 0) {
                    electricEquips.append(",");
                }
                electricEquips.append(mData.getElectricEquips().get(index).getId());
            }
        }

        StringBuffer energyEquips = new StringBuffer();
        for (Integer index : selectEnergyEquipIndex) {
            if (index != -1) {
                if (energyEquips.length() > 0) {
                    energyEquips.append(",");
                }
                energyEquips.append(mData.getEnergyEquips().get(index).getId());
            }
        }
//        ToastUtils.show("任务名称 = " + taskContent + " circuitId = " + circuitId + " regionId = " + regionId + " equipId = " + equipId + " electricEquips = " + electricEquips.toString() + " energyEquips = " + energyEquips.toString());
        TaskApplyResult applyResult = new TaskApplyResult(loginData.getId(), taskContent, circuitId, regionId, equipId, electricEquips.toString(), energyEquips.toString());
        EasyHttp.post(this)
                .api(new TaskApplyAddApi())
                .json(gson.toJson(applyResult))
                .request(new HttpCallback<HttpData<TaskApplyAddApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<TaskApplyAddApi.Bean> result) {
                        ToastUtils.show("提交成功");
                        Log.d("ApplyFragment", "result = " + result.getData());
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }

                });

    }

    /**
     * 弹框确认, 误操作
     */
    private void cleanData() {
        mEtTaskContent.setText(null);
        mLineDoubleNameSb.setRightText(null);
        mAreaSb.setRightText(null);
        mBreakerNum.setRightText(null);
        mPowerAdapter.clearData();
        mStoredAdapter.clearData();
        currentCircuitIndex = -1;
        currentRegionIndex = -1;
        currentEquipIndex = -1;
        selectElectricEquipIndex.clear();
        selectEnergyEquipIndex.clear();
    }

    /**
     * 接口请求不同数据源
     *
     * @param type
     */
    private void selectPowerList(int type) {
        String title = type == 0 ? "发电低压断路器编号 （多选）" : "储能低压断路器编号 （多选）";
        if (mData == null) {
            return;
        }
        List<TaskApplyEquipData> listData = type == 0 ? mData.getElectricEquips() : mData.getEnergyEquips();
        List<Integer> selectListIndex = type == 0 ? selectElectricEquipIndex : selectEnergyEquipIndex;
        if (listData != null && listData.size() > 0) {
            List<String> equipStringList = new ArrayList<>();
            for (TaskApplyEquipData bean : listData) {
                equipStringList.add(bean.getEquipName());
            }

            int[] selectIndex = new int[selectListIndex.size()];
            if (selectListIndex.size() > 0) {
                for (int i = 0; i < selectListIndex.size(); i++) {
                    selectIndex[i] = selectListIndex.get(i);
                }
            }
            new MultiMenuDialog.Builder(getAttachActivity())
                    .setGravity(Gravity.BOTTOM)
                    .setTitle(title)
                    .setList(equipStringList)
                    .setSelect(selectIndex)
                    .setListener((dialog, selectData) -> {
                        List<TaskApplyEquipData> selectDataList = new ArrayList<>();
                        List<Integer> selectIndexList = type == 0 ? selectElectricEquipIndex : selectEnergyEquipIndex;
                        selectIndexList.clear();
                        ApplyBreakerNumAdapter adapter = type == 0 ? mPowerAdapter : mStoredAdapter;
                        for (Object value : selectData.values()) {
                            TaskApplyEquipData data = new TaskApplyEquipData(0, 0, null, value.toString(), 0, null);
                            if (listData.contains(data)) {
                                int index = listData.indexOf(data);
                                if (index != -1) {
                                    selectIndexList.add(index);
                                    selectDataList.add(listData.get(index));
                                }
                            }
                        }
                        adapter.setData(selectDataList);
                    })
                    .show();
        }

    }

    private void selectBreakerNum() {
        if (mData.getEquips() != null && mData.getEquips().size() > 0) {
            List<String> equipStringList = new ArrayList<>();
            for (TaskApplyEquipData bean : mData.getEquips()) {
                equipStringList.add(bean.getEquipName());
            }
            // 底部选择框
            new MenuDialog.Builder(getAttachActivity())
                    // 设置 null 表示不显示取消按钮
                    //.setCancel(getString(R.string.common_cancel))
                    // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setCancel(null)
                    .setList(equipStringList)
                    .setListener(new MenuDialog.OnListener<String>() {

                        @Override
                        public void onSelected(BaseDialog dialog, int position, String string) {
//                            toast("位置：" + position + "，文本：" + string);
                            currentEquipIndex = position;
                            mBreakerNum.setRightText(string);
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
//                            toast("取消了");
                        }
                    })
                    .show();
        }
    }

    private void selectArea() {
        if (mData.getRegions() != null && mData.getRegions().size() > 0) {
            List<String> regionStringList = new ArrayList<>();
            for (TaskApplyRegionData bean : mData.getRegions()) {
                regionStringList.add(bean.getRegionName());
            }
            // 底部选择框
            new MenuDialog.Builder(getAttachActivity())
                    // 设置 null 表示不显示取消按钮
                    //.setCancel(getString(R.string.common_cancel))
                    // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setCancel(null)
                    .setList(regionStringList)
                    .setListener(new MenuDialog.OnListener<String>() {

                        @Override
                        public void onSelected(BaseDialog dialog, int position, String string) {
//                            toast("位置：" + position + "，文本：" + string);
                            currentRegionIndex = position;
                            mAreaSb.setRightText(string);
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
//                            toast("取消了");
                        }
                    })
                    .show();
        }
    }

    /**
     * 加载线路数据
     */
    private void selectLineDoubleName() {
        if (mData != null && mData.getCircuits() != null && mData.getCircuits().size() > 0) {
            List<String> lineStringList = new ArrayList<>();
            for (TaskApplyCircuitData bean : mData.getCircuits()) {
                lineStringList.add(bean.getCircuitName());
            }
            // 底部选择框
            new MenuDialog.Builder(getAttachActivity())
                    // 设置 null 表示不显示取消按钮
                    //.setCancel(getString(R.string.common_cancel))
                    // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setCancel(null)
                    .setList(lineStringList)
                    .setListener(new MenuDialog.OnListener<String>() {

                        @Override
                        public void onSelected(BaseDialog dialog, int position, String string) {
//                            toast("位置：" + position + "，文本：" + string);
                            currentCircuitIndex = position;
                            mLineDoubleNameSb.setRightText(string);
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
//                            toast("取消了");
                        }
                    })
                    .show();
        }
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    /**
     * CollapsingToolbarLayout 渐变回调
     * <p>
     * {@link XCollapsingToolbarLayout.OnScrimsListener}
     */
    @SuppressLint("RestrictedApi")
    @Override
    public void onScrimsStateChange(XCollapsingToolbarLayout layout, boolean shown) {
        getStatusBarConfig().statusBarDarkFont(shown).init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}